const express = require("express");
const router = express.Router();
const visitorController = require("../controllers/visitorController");
const { verifyVisitorToken } = require("../middlewares/authMiddleware");
const userRoutes = require("./users");
const multer = require("multer");
const path = require("path");
const fs = require("fs");
const { v4: uuidv4 } = require("uuid");

// 配置multer用于头像上传
const avatarStorage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = "uploads/";
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名
    const uniqueName = uuidv4() + path.extname(file.originalname);
    cb(null, uniqueName);
  },
});

const uploadAvatar = multer({
  storage: avatarStorage,
  limits: {
    fileSize: 5 * 1024 * 1024, // 限制5MB，适合头像文件
  },
  fileFilter: (req, file, cb) => {
    // 只允许图片类型
    const allowedImageTypes = [
      "image/jpeg",
      "image/jpg",
      "image/png",
      "image/gif",
      "image/webp",
      "image/bmp",
    ];
    if (allowedImageTypes.includes(file.mimetype)) {
      return cb(null, true);
    } else {
      cb(new Error("只支持图片格式文件（jpg, png, gif, webp, bmp）"), false);
    }
  },
});

// 错误处理中间件
const handleAvatarUploadError = (error, req, res, next) => {
  if (error instanceof multer.MulterError) {
    if (error.code === "LIMIT_FILE_SIZE") {
      return res.status(400).json({
        success: false,
        error: "文件大小超过限制（最大5MB）",
        code: "FILE_TOO_LARGE",
      });
    }
  }
  if (error.message.includes("只支持图片格式文件")) {
    return res.status(400).json({
      success: false,
      error: error.message,
      code: "INVALID_FILE_TYPE",
    });
  }
  next(error);
};

// 公开路由
//注册正式用户（步骤1：发送验证码）
router.post("/addUser", visitorController.registerUser);

//验证邮箱验证码并完成注册（步骤2）
router.post("/verifyEmailAndRegister", visitorController.verifyEmailAndRegister);

// 注册新访客
router.post("/register", visitorController.register);

// 邮箱+密码登录
router.post("/loginUser", visitorController.loginWithEmail);

// 访客登录
router.post("/login", visitorController.login);

// 生成新UUID（辅助接口）
router.get("/generate-uuid", visitorController.generateUuid);

// 受保护路由 - 需要有效的JWT令牌
// 获取当前访客信息
router.get("/profile", verifyVisitorToken, (req, res) => {
  return res.status(200).json({
    success: true,
    message: "获取访客信息成功",
    data: req.visitor,
  });
});

// 验证令牌是否有效
router.get("/verify-token", verifyVisitorToken, (req, res) => {
  return res.status(200).json({
    success: true,
    message: "令牌有效",
    data: {
      uuid: req.visitor.uuid,
      isValid: true,
    },
  });
});

// 获取用户信息（加密返回）
router.get(
  "/getUserInformation",
  verifyVisitorToken,
  visitorController.getUserInformation
);

// 修改用户信息（displayName, gender, phone）
router.post(
  "/updateUserInformation",
  verifyVisitorToken,
  visitorController.updateUserInformation
);

// 修改用户密码
router.post(
  "/updateUserPassword",
  verifyVisitorToken,
  visitorController.updateUserPassword
);

// 修改用户头像
router.post(
  "/updateUserAvatar",
  uploadAvatar.single("avatar"),
  handleAvatarUploadError,
  visitorController.updateUserAvatar
);

// 新增：用户自助发送邮件
router.post("/sendMailToSelf", visitorController.sendMailToSelf);

// 查询tokens_balance（通过uuid请求头）
router.get(
  "/getTokensBalanceByUuid",
  verifyVisitorToken,
  visitorController.getTokensBalanceByUuid
);

// 注册用户相关路由
router.use("/users", userRoutes);

// Stripe 支付路由

// 忘记密码：请求重置密码邮件
router.post("/request-password-reset", visitorController.requestPasswordReset);
// 忘记密码：重置密码
router.post("/reset-password", visitorController.resetPassword);

module.exports = router;
